import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';

void main() {
  printName();
  moreThenOneJobWait();

  microTaskTest();

  newIsolateTest();
}

void microTask() {
  print("microTask");
}

void microTaskTest() {
  scheduleMicrotask(microTask);
  Future.microtask(microTask);
}

Future<void> printName() async {
  String name = await getNameFromNet();
  print(name);
}

Future<String> getNameFromNet() async {
  await Future.delayed(Duration(milliseconds: 5000));
  return "name";
}

// http://www.5imoban.net/jiaocheng/dart/2020/0927/3986.html
// 用future实现等待多个任务完成后，再得到所有的执行结果
void moreThenOneJobWait() {
  print('start');

  Future task1 = Future(() async {
    await Future.delayed(Duration(milliseconds: 1000));
    print('task1');
    return 1;
  });

  Future task2 = Future(() async {
    await Future.delayed(Duration(milliseconds: 2000));
    print('task2');
    return 2;
  });

  Future task3 = Future(() async {
    await Future.delayed(Duration(milliseconds: 3000));
    print('task3');
    return 3;
  });

  Future future = Future.wait([task1, task2, task3]);

  future.then((value) {
    print(value);
  });

  print('end');

  //执行结果：
  //start
  //end
  //task1
  //task2
  //task3
  //[1, 2, 3]
}

// 创建一个新的Isolate，在其中运行任务doWork
newIsolateTest() async {
  var str = "New Task";
  var result = await compute(doWork, str);
  print(result);
}

String doWork(String value) {
  print("new isolate doWork start");
  // 模拟耗时5秒
  sleep(Duration(seconds: 5));

  print("new isolate doWork end");
  return "complete:$value";
}
